package cn.edu.cug.cs.gtl.plugins.device.actions;

import cn.edu.cug.cs.gtl.apis.ui.AbstractApplication;
import cn.edu.cug.cs.gtl.apis.ui.actions.AbstractAction;
import cn.edu.cug.cs.gtl.apis.ui.datake.devicetree.DeviceTree;
import cn.edu.cug.cs.gtl.apis.ui.tree.TreeNodeData;
import cn.edu.cug.cs.gtl.plugins.device.common.DBUtils;
import cn.edu.cug.cs.gtl.plugins.device.dialog.StorageClusterDialog;
import cn.edu.cug.cs.gtl.protos.StorageCluster;
import cn.edu.cug.cs.gtl.utils.impl.DataDeviceManagerImpl;

import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
import java.awt.event.ActionEvent;
import java.util.Locale;
import java.util.ResourceBundle;

public class NewComputingClusterAction extends AbstractAction {
    DBUtils dbUtils = new DBUtils();

    @Override
    public void initialize(AbstractApplication theApp) {
        ResourceBundle resourceBundle = ResourceBundle.getBundle("device-resource", Locale.getDefault());

        name = resourceBundle.getString("popupmenu.device.tree.new_computing_cluster");
        menuItem.setText(name);


        this.theApp = theApp;
        menuItem.addActionListener(this);
        // 添加分割符
        //((DeviceTree) theApp.getMainFrame().asDatakeFrame().getDevicePanel().getTreeComponent()).getStorageClusterNodePopupMenu().addSeparator();
        ((DeviceTree) theApp.getMainFrame().asDatakeFrame().getDevicePanel().getTreeComponent()).getStorageClusterNodePopupMenu().add(menuItem);
    }

    /**
     * Invoked when an action occurs.
     *
     * @param e the event to be processed
     */
    @Override
    public void actionPerformed(ActionEvent e) {
        // 弹出窗口，获取用户输入的集群配置信息
        StorageClusterDialog clusterDialog = new StorageClusterDialog((JFrame) SwingUtilities.getWindowAncestor(menuItem));
        clusterDialog.setVisible(true);

        // 获取输入的集群配置信息
        String connectionName = clusterDialog.getConnectionName();
        String url = clusterDialog.getUrl();
        String user = clusterDialog.getUser();
        String password = clusterDialog.getPassword();

        // Perform the connection test (you need to implement this method)
        boolean isConnected = false;

        if (clusterDialog.isConfirmed()) {
            //获取当前选中的节点的数据，进而判断使用哪个对应的方法
            Object obj = theApp.getMainFrame().asDatakeFrame().getDevicePanel().getTreeComponent().getCurrentReferencedObject();
            if (obj.equals("Hadoop HDFS")) {
                isConnected = dbUtils.connectionForHDFS(url, user, password);
            } else if (obj.equals("MinIO")) {
                isConnected = dbUtils.connectionForMinIo(url, user, password);
            } else if (obj.equals("PostgreSQL")) {
                isConnected = dbUtils.connectionForPostgreSQL(url, user, password);
            } else if (obj.equals("MySQL")) {
                isConnected = dbUtils.connectionForMySQL(url, user, password);
            } else if (obj.equals("Oracle")) {
                isConnected = dbUtils.connectionForOracle(url, user, password);
            } else if (obj.equals("MongoDB")) {
                isConnected = dbUtils.connectionForMongoDB(url, user, password);
            }

            // 显示结果信息
            if (isConnected) {
                String message = "添加存储集群成功！";
                String title = "连接成功";
                JOptionPane.showMessageDialog(null, message, title, JOptionPane.INFORMATION_MESSAGE);

                //连接成功，则将配置信息保存
                StorageCluster storageCluster = StorageCluster.newBuilder()
                        .setName(connectionName)
                        .setAlias(connectionName)
                        .setType(obj.toString())
                        .setUrl(url)
                        .setUserName(user)
                        .setPassword(password)
                        .build();

                saveStorageClusterNode(storageCluster);
            } else {
                String message = "添加存储集群失败，请检查配置信息是否正确！";
                String title = "连接失败";
                JOptionPane.showMessageDialog(null, message, title, JOptionPane.ERROR_MESSAGE);
            }

        }

    }

    //将输入的配置信息保存为节点对象，并且存入数据库中
    public void saveStorageClusterNode(StorageCluster storageCluster) {
        DeviceTree tree = (DeviceTree) theApp.getMainFrame().asDatakeFrame().getDevicePanel().getTreeComponent();
        DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();

        //插入数据库中
        DataDeviceManagerImpl dataDeviceManager = new DataDeviceManagerImpl();
        dataDeviceManager.insertStorageCluster(storageCluster);

        //保存为结点对象
        DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(new TreeNodeData(storageCluster, storageCluster.getAlias(), true));

        //将新节点newNode作为选中节点selectedNode的最后子节点添加到树中，并通知树的视图。
        DefaultTreeModel treeModel = (DefaultTreeModel) tree.getModel();
        treeModel.insertNodeInto(newNode, selectedNode, selectedNode.getChildCount());

        //将新节点变为可视
        TreeNode[] nodes = treeModel.getPathToRoot(newNode);
        tree.scrollPathToVisible(new TreePath(nodes));    //构造一个从根节点到新添加节点的树路径，由于我们的树放在一个滚动面板中，这样会告诉外围的滚动面板将路径末端的节点滚动到视图中在·
//        tree.expandPath(tree.getSelectionPath());

    }

}
